<?php

namespace app\api\model;

use think\Hook;
use app\common\model\Course as CourseModel;

class Course extends CourseModel
{
    public function setDateAttr($value)
    {
        return $value ? date('Y-m-d', strtotime($value)) : '';
    }

    /**
     * 创建课表
     */
    public function addAll(array $data)
    {
        return $this->allowField(true)->saveAll($data);
    }

    /**
     * 用户课表
     */
    public static function getByUserId($userId, $status, $size = 20)
    {
        $courses = self::with(['teacher' => function ($query) {
            $query->withCount('course');
        }, 'courseOrder'])->where('user_id', $userId)->whereIn('status', $status)->order(['date asc', 'index asc'])->paginate($size);
        $items = self::lists($courses->items());
        return [
            'course' => $items,
            'total' =>  $courses->total(),
        ];
    }

    /**
     * 待预约
     * @param $courseOrderId
     * @return int|mixed
     */
    public static function waitCourse($userId)
    {
        $courses = self::with(['teacher' => function ($query) {
            $query->withCount('course');
        }, 'courseOrder'])->where('user_id', $userId)->where('status', 2)->order(['date asc', 'index asc'])->select();
        $data = [];
        foreach ($courses as $val) {
            if ($val['index'] <= self::getMinIndex($val['course_order_id'])) {
                $data[] = $val;
            }
        }
        return [
            'course' => self::lists($data),
            'total' =>  count($data),
        ];
    }


    public  static function getMinIndex($courseOrderId)
    {
        $index = self::where('course_order_id', $courseOrderId)->where('status', 2)->column('index');
        return $index ? min($index) : 0;
    }

    /**
     * 课时
     */
    public static function getCourseNums($userId, $status)
    {
        return self::where('user_id', $userId)->where('status', $status)->count();
    }

    /**
     * 更新课表状态
     */
    public static function updateByOrderId($courseOrderId, $data)
    {
        return self::where('course_order_id', $courseOrderId)->update($data);
    }

    public static function getByOrderId($courseOrderId)
    {
        return self::where('course_order_id', $courseOrderId)->find();
    }

    /**
     * 课程预约时间段
     */
    public static function getTimes($teacherCourseId, $date)
    {
        return self::where('teacher_course_id', $teacherCourseId)->where('date', $date)->where('status', 3)->column('time');
    }

    /**
     * 获取订单课表的数量
     */
    public static function getCourseOrderCount($courseOrderId, $status)
    {
        return self::where('course_order_id', $courseOrderId)->where('status', $status)->count();
    }

    /**
     * @param $userId
     * @param $column
     * @return array|bool|string
     */
    public static function getColumnByUserId($userId, $status, $column)
    {
        return self::where('user_id', $userId)->where('status', $status)->column($column);
    }

    /**
     * 累积天数
     */
    public static function getdays($userId)
    {
        $days = self::getColumnByUserId($userId, 4, 'date');
        return count(array_unique($days));
    }

    /**
     * 累积课时
     */
    public static function getHours($userId)
    {
        $times = self::getColumnByUserId($userId, 4, 'time');
        $hour = 0;
        foreach ($times as $val) {
            if (!$val) {
                continue;
            }
            $hour += self::getHour($val);
        }
        return $hour;
    }

    /**
     * 累积课次
     */
    public static function getCourseCounts($userId)
    {
        return self::where('user_id', $userId)->whereIn('status', 4)->count();
    }

    /**
     * 用户课程记录
     */
    public static function getUserLog($userId, $size = 20)
    {
        $logs = self::with(['teacherCourse' => function ($query) {
            $query->with(['language', 'teacher', 'grade'])->withCount('course');
        }])->where('user_id', $userId)->where('status', 4)->paginate($size);
        foreach ($logs as $val) {
            if (!$val['time']) {
                continue;
            }
            $val['hour'] = self::getHour($val['time']);
        }
        return $logs;
    }

    /**
     * 获取课表
     */
    public static function getByCourseOrderIdAndStatus($courseOrderId, $status)
    {
        return self::where('course_order_id', $courseOrderId)->whereIn('status', $status)->select();
    }

    /**
     * 课程剩余课次
     */
    public static function getSurplusCourseId($courseOrderId)
    {
        $course = self::getByCourseOrderIdAndStatus($courseOrderId, [2, 3]);
        $courseId = [];
        foreach ($course as $key=>$val) {
            //剔除已上课
            if (!self::isStart($val['date'], $val['time'], $val['status'])) {
                $courseId[] = $val['course_id'];
            }
        }
        return $courseId;
    }

    /**
     * 更新
     */
    public static function updateStatus($courseId, $status)
    {
        return self::whereIn('course_id', $courseId)->update(['status' => $status]);
    }

    /**
     * 回退课表状态
     */
    public static function rollbackStatus($courseOrderId)
    {
        $course = self::getByCourseOrderIdAndStatus($courseOrderId, [5]);
        if ($course) {
            foreach ($course as &$val) {
                if ($val['date'] && $val['time']) {
                    $val->status = 3;
                } else {
                    $val->status = 2;
                }
                $val->save();
            }
        }
    }

    /**
     * 部分预约 - 预约时间
     */
    public static function getOrtherReserve($courseOrderId)
    {
        $courses = self::where('course_order_id', $courseOrderId)->where('status', '>', 2)->order('index desc')->select();
        array_walk($courses, function (&$val) {
            $val['is_start'] = self::isStart($val['date'], $val['time'], $val['status']);
        });
        return $courses;
    }

    /**
     * 待预约的课程ID
     */
    public static function waitCourseId($courseOrderId)
    {
        return self::where('course_order_id', $courseOrderId)->where('status', 2)->order('index asc')->column('course_id');
    }
}
